package com.app.bimo.commonbusiness.network;


import com.app.bimo.commonbusiness.mvp.IView;
import com.app.bimo.commonbusiness.network.Exception.ApiException;

import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

public class HttpErrorUtil {
    private HttpErrorUtil() {
        throw new IllegalStateException("Can't instance the HttpErrorUtil");
    }

    /**
     * 接口返回错误时候的统一处理
     *
     * @param mRootView
     */
    public static Consumer<Throwable> handleError(IView mRootView) {
        return throwable -> {

            ApiException exception = (ApiException) throwable;
            if (exception.getCode() == 401) {
                mRootView.showLogin();
            } else if (exception.getCode() >= 500) {
                //展示网络错误页面
                mRootView.showMessage("网络异常");
            } else {
                //40x提示返回的msg
                mRootView.showMessage(exception.getDisplayMessage());
            }
        };
    }

    /**
     * 接口返回错误时候的统一处理
     *
     * @param mRootView
     */
    public static Consumer<Throwable> handleError(IView mRootView, Action action) {
        return throwable -> {
            action.run();
            mRootView.hideLoading();

            ApiException exception = (ApiException) throwable;
            if (exception.getCode() == 401) {
                mRootView.showLogin();
            } else if (exception.getCode() >= 500) {
                //展示网络错误页面
                mRootView.showMessage("网络异常");
            } else {
                //40x提示返回的msg
                mRootView.showMessage(exception.getDisplayMessage());
            }
        };
    }
}
